import { useCallback, useEffect, useState } from 'react';
import { useGame } from '../GameContext';
import { PizzaType } from '../types';

/**
 * 自定义Hook，封装游戏的核心逻辑
 */
export const useGameLogic = () => {
  const { state, deliverPizza, takePizzaFromOven } = useGame();
  const [draggedPizza, setDraggedPizza] = useState<PizzaType | null>(null);
  const [isDragging, setIsDragging] = useState(false);

  // 检查订单是否超时
  const checkOrderTimeouts = useCallback(() => {
    if (!state.gameActive) return;
    
    const currentTime = Date.now();
    return state.orders.map(order => {
      if (order.status === 'pending' || order.status === 'in-progress') {
        const timeElapsed = (currentTime - order.createdAt) / 1000;
        const remainingTime = Math.max(0, order.timeLimit - timeElapsed);
        const isUrgent = remainingTime < 10;
        
        return {
          ...order,
          remainingTime,
          isUrgent
        };
      }
      return order;
    });
  }, [state.gameActive, state.orders]);

  // 检查烤炉状态
  const checkOvenStatus = useCallback(() => {
    if (!state.gameActive) return state.ovenSlots;
    
    const currentTime = Date.now();
    return state.ovenSlots.map(slot => {
      if (slot.status === 'baking' && slot.startTime && slot.pizza) {
        const elapsedTime = (currentTime - slot.startTime) / 1000;
        const bakeTime = slot.pizza ? 20 : 15; // 默认烘烤时间
        const remainingTime = Math.max(0, bakeTime - elapsedTime);
        
        return {
          ...slot,
          remainingTime,
          progress: (elapsedTime / bakeTime) * 100
        };
      }
      return slot;
    });
  }, [state.gameActive, state.ovenSlots]);

  // 处理披萨拖拽
  const handlePizzaDragStart = useCallback((pizzaType: PizzaType) => {
    setDraggedPizza(pizzaType);
    setIsDragging(true);
  }, []);

  const handlePizzaDragEnd = useCallback(() => {
    setIsDragging(false);
  }, []);

  // 处理披萨交付
  const handlePizzaDelivery = useCallback((orderId: string, slotId: number) => {
    const pizzaType = takePizzaFromOven(slotId);
    if (pizzaType) {
      const success = deliverPizza(orderId, pizzaType);
      setDraggedPizza(null);
      return success;
    }
    return false;
  }, [takePizzaFromOven, deliverPizza]);

  // 检查游戏是否结束
  useEffect(() => {
    if (state.reputation <= 0 && state.gameActive) {
      // 游戏结束逻辑已经在GameContext中处理
    }
  }, [state.reputation, state.gameActive]);

  return {
    checkOrderTimeouts,
    checkOvenStatus,
    draggedPizza,
    isDragging,
    handlePizzaDragStart,
    handlePizzaDragEnd,
    handlePizzaDelivery
  };
};